var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/DeptTreeSelect/hooks/index.ts
var hooks_exports = {};
__export(hooks_exports, {
  default: () => useDeptTree
});
module.exports = __toCommonJS(hooks_exports);
var import_react = require("react");
var import_hooks = require("@szzj/hooks");
var import_dept = require("../../../services/dept");
function useDeptTree({
  drsAppCode,
  authed,
  initDeptDeep,
  isSubApp,
  customDetailRequestUrl
}) {
  const [searchExpandedKeys, setSearchExpandedKeys] = (0, import_react.useState)([]);
  const {
    data: initialTreeNodes = [],
    loading,
    fetch: fetchInitialTree
  } = (0, import_hooks.useFetch)(
    () => authed ? (0, import_dept.getDeptInitialTreeAuthed)(
      {
        appCode: drsAppCode,
        hasDataPerm: true
      },
      isSubApp
    ) : (0, import_dept.getDeptInitialTree)(
      { appCode: drsAppCode, deptDeep: initDeptDeep },
      isSubApp
    ),
    {
      manual: true,
      useData: true,
      defaultData: []
    }
  );
  const allInInitialTree = (0, import_react.useMemo)(() => {
    return initialTreeNodes.length && !initialTreeNodes.some((node) => {
      var _a;
      return (_a = node.children) == null ? void 0 : _a.length;
    });
  }, [initialTreeNodes]);
  const { treeNodes, append, findNode, findAncestorNodes, filter, toArray } = (0, import_hooks.useTree)(initialTreeNodes, {
    uniqueKey: "key",
    childrenKey: "children"
  });
  const appendRef = (0, import_hooks.useRealtimeRef)(append);
  const {
    data: deptNodeDetail,
    fetch: fetchDeptNodeDetail,
    loading: detailLoading
  } = (0, import_hooks.useFetch)(
    (deptCode) => {
      return (0, import_dept.getDeptDetail)(
        { deptCode, appCode: drsAppCode },
        { isSubApp, customDetailRequestUrl }
      );
    },
    {
      manual: true,
      useData: true
    }
  );
  const loadDeptNodesByParentCode = (0, import_react.useCallback)(
    (parentDeptCode) => {
      return (0, import_dept.queryChildDeptTreeNodes)(
        {
          appCode: drsAppCode,
          deptCode: parentDeptCode
        },
        isSubApp
      ).then((res) => {
        var _a;
        if (res == null ? void 0 : res.success) {
          (((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.list) ?? []).forEach(
            (childNode) => appendRef.current(childNode, parentDeptCode)
          );
        }
        return res;
      });
    },
    [append]
  );
  const loadData = (0, import_react.useCallback)(
    (node) => {
      var _a, _b;
      if (allInInitialTree || ((_b = (_a = findNode(node.key)) == null ? void 0 : _a.children) == null ? void 0 : _b.length) || node.isLeaf)
        return Promise.resolve();
      return loadDeptNodesByParentCode(node.key);
    },
    [allInInitialTree, findNode, loadDeptNodesByParentCode]
  );
  const loadingDetailKeyRef = (0, import_react.useRef)(false);
  const loadDeptNodesByDetail = (0, import_react.useCallback)(async () => {
    var _a;
    if (!allInInitialTree && treeNodes.length && (deptNodeDetail == null ? void 0 : deptNodeDetail.key) && !loadingDetailKeyRef.current) {
      loadingDetailKeyRef.current = true;
      const deptCodes = (_a = deptNodeDetail == null ? void 0 : deptNodeDetail.codePath) == null ? void 0 : _a.split("/");
      let matchInitialTreeNode = false;
      if (!deptCodes) {
        return;
      }
      for (const deptCode of deptCodes) {
        const index = deptCodes.indexOf(deptCode);
        const parentKey = deptCodes[index - 1];
        if (treeNodes.some((node) => node.key === parentKey)) {
          matchInitialTreeNode = true;
        }
        if (!findNode(deptCode) && parentKey && matchInitialTreeNode) {
          await loadDeptNodesByParentCode(parentKey);
        }
      }
    }
  }, [
    allInInitialTree,
    treeNodes,
    deptNodeDetail,
    findNode,
    loadDeptNodesByParentCode
  ]);
  (0, import_react.useEffect)(() => {
    loadDeptNodesByDetail();
  }, [loadDeptNodesByDetail]);
  const [treeNodesBySearch, setTreeNodesBySearch] = (0, import_react.useState)(
    []
  );
  const { fetch: searchTreeNodesByName } = (0, import_hooks.useFetch)(
    (deptName) => {
      setTreeNodesBySearch([]);
      if (authed) {
        return (0, import_dept.searchByNameAuthed)(
          { appCode: drsAppCode, deptName },
          isSubApp
        ).then((res) => {
          if ((res == null ? void 0 : res.success) && (res == null ? void 0 : res.data)) {
            setSearchExpandedKeys(
              toArray(filter(res.data, (itemNode) => !itemNode.isLeaf)).map(
                (item) => item.key
              )
            );
            setTreeNodesBySearch(res == null ? void 0 : res.data);
          }
          return res;
        });
      }
      return (0, import_dept.searchByName)({ appCode: drsAppCode, deptName }, isSubApp).then(
        (res) => {
          if ((res == null ? void 0 : res.success) && (res == null ? void 0 : res.data)) {
            setSearchExpandedKeys(
              toArray(filter(res.data, (itemNode) => !itemNode.isLeaf)).map(
                (item) => item.key
              )
            );
            setTreeNodesBySearch(res == null ? void 0 : res.data);
          }
          return res;
        }
      );
    },
    {
      manual: true
    }
  );
  return {
    fetchInitialTree,
    treeNodes,
    findNode,
    findAncestorNodes,
    loadData,
    loading,
    detailLoading,
    fetchDeptNodeDetail,
    treeNodesBySearch,
    searchTreeNodesByName,
    searchExpandedKeys,
    loadingDetailKeyRef,
    clearTreeNodesBySearch: () => setTreeNodesBySearch([])
  };
}
